# -*- coding: utf-8 -*-
import cgi
import os 
import datetime
import time
import wsgiref.handlers
import string

import django

from time import strftime, localtime 
from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
from loginTool import login_required

class Subscribe(db.Model):  #//用户订阅表,第一层数据
  userName = db.StringProperty(multiline=True)#//订阅人
  maincode  = db.StringProperty(multiline=True) #存第一级内容编号，后面的表都加上  
  #contentCode = db.StringProperty(multiline=True)#//订阅内容编号
  subscribeType = db.StringProperty(multiline=True)#//0 表示下面的全要。1 表示下面的另外订阅说明。
  lastUpdateTime = db.DateTimeProperty(auto_now_add=True) #//上次更新时间。
  status=db.StringProperty(multiline=True) #//0 取消订阅了，还没真正物理删除。1 订阅
#  DownLastUpdateTime=db.DateTimeProperty(auto_now_add=True) #//订阅改变时间
  #date = db.DateTimeProperty(auto_now_add=True)  #//订阅时间

class SubscribeOther(db.Model):#//用户订阅表,其它层
  userName = db.StringProperty(multiline=True)#//订阅人
  maincode  = db.StringProperty(multiline=True) #存第一级内容编号，后面的表都加上 
  code = db.StringProperty(multiline=True)#//订阅内容编号
  father = db.StringProperty(multiline=True)#//上一级内容编号
  level = db.StringProperty(multiline=True)#// 级别 2-5
  subscribeType = db.StringProperty(multiline=True)#//0 表示下面的全要。  1 表示下面的另外订阅说明。


class PublicPage(webapp.RequestHandler):
    def render(self, template_file, template_value):
        path = os.path.join(os.path.dirname(__file__), template_file)
        self.response.out.write(template.render(path, template_value))

class SubscribeInfo(PublicPage):
    @login_required
    def get(self):
        searchType = self.request.get('searchType')#'searchType‘不存在是返回的不是None，而是''空字符
#        template_values = {'searchType':searchType,}
        self.redirect("/subscribeList?searchType=%s" %searchType)
#        self.render('html/subscribeManage/subscribeInfo.html',template_values)#本地上运行用这个
    @login_required
    def post(self):
        searchType = self.request.get('searchType')
        self.redirect('/subscribeInfo?searchType=%s' %searchType)

class SubscribeList(PublicPage):
    @login_required
    def get(self):
        searchType = self.request.get('searchType')#'searchType‘不存在是返回的不是None，而是''空字符
        if searchType=='':
            subscribes =[]
        elif searchType=='userName':
            subscribes = db.GqlQuery("SELECT * "
                                    "FROM Subscribe "
                                    "ORDER BY %s DESC ,maincode LIMIT 100" %searchType)
            searchType=''
        else:
            subscribes = db.GqlQuery("SELECT * "
                                    "FROM Subscribe "
                                    "WHERE userName=:1 ORDER BY  maincode",searchType)
            
        template_values = {'subscribes':subscribes,'searchType':searchType}
        self.render('template/subscribe/subscribeInfo.html',template_values)#本地上运行用这个
#        self.render('html/subscribeManage/subscribeList.html',template_values)#本地上运行用这个


class SubscribeAdd(PublicPage):
    @login_required
    def get(self):
        users = db.GqlQuery("SELECT * FROM User ORDER BY userName ASC")
        template_values = {'users':users,}
        self.render('template/subscribe/subscribeAdd.html',template_values)#本地上运行用这个
#        self.render('html/subscribeManage/subscribeAdd.html',template_values)#本地上运行用这个
    @login_required
    def post(self):
        greeting = Subscribe()
        maincode = greeting.maincode = self.request.get('maincode')
        userName = greeting.userName = self.request.get('userName')
        
        subscribes = db.GqlQuery("SELECT * FROM Subscribe WHERE maincode=:1 AND userName=:2",maincode,userName)
        subscribe = subscribes.fetch(1,0)
        if subscribe:
            self.redirect('/userSubscribeAdd?userName=%s' %userName)
            return
#        subscribeType = 
        greeting.subscribeType = self.request.get('subscribeType')
        greeting.status = '1'
        greeting.put()
        self.redirect('/subscribeInfo?searchType=%s' %userName)

class UserSubscribeAdd(PublicPage):
    @login_required
    def get(self):
        userName = self.request.get('userName')
        father = self.request.get('father')
        code=self.request.get('code')
        if father:
            contents = []
            if code:
                replyContents = db.GqlQuery("SELECT * FROM ReplyContent WHERE father=:1 and status='1' and code>=:2 AND code<=:3 ORDER BY code ASC",father,code,u""+code+"" + u"\ufffd")
                conts = db.GqlQuery("SELECT * FROM ContentClass WHERE father=:1 and status='1' and code>=:2 AND code<=:3 ORDER BY code ASC",father,code,u""+code+"" + u"\ufffd")
            else:
                replyContents = db.GqlQuery("SELECT * FROM ReplyContent WHERE father=:1 and status='1' ORDER BY code ASC",father)
                conts = db.GqlQuery("SELECT * FROM ContentClass WHERE father=:1 and status='1' ORDER BY code ASC",father)
            
            if replyContents:
                for replyContent in replyContents:
                    contents.append(replyContent)
            if conts:
                for cont in conts:
                    contents.append(cont)
#            contents = db.GqlQuery("SELECT * FROM ContentClass WHERE father=:1 and status='1' ORDER BY code ASC",father)
        else:
            if code:
                contents = db.GqlQuery("SELECT * FROM ContentClass WHERE level='1' and status='1' and code>=:1 AND code<=:2 ORDER BY code ASC",code,u""+code+"" + u"\ufffd")
            else:
                contents = db.GqlQuery("SELECT * FROM ContentClass WHERE level='1' and status='1' ORDER BY code ASC")
        template_values = {'userName':userName,"contents":contents,'father':father,'code':code}
        self.render('template/subscribe/userSubscribeAdd.html',template_values)#本地上运行用这个
#        self.render('html/subscribeManage/userSubscribeAdd.html',template_values)#本地上运行用这个

class SubscribeDelete(PublicPage):
    @login_required
    def get(self):
        maincode = self.request.get('maincode')
        userName = self.request.get('userName')
        subscribes = db.GqlQuery("SELECT * FROM Subscribe WHERE userName=:1 AND maincode=:2",userName,maincode)
        if (subscribes):
            contentList = []
            for subscribe in subscribes:
                contentList.append(subscribe)
                contentList=findSubscribeOthers(contentList,userName,maincode)
        for cList in contentList:
            db.delete(cList)
        self.redirect('/subscribeList?searchType=%s' %userName)

class SubscribeStatus(PublicPage):
    @login_required
    def get(self):
        maincode = self.request.get('maincode')
        userName = self.request.get('userName')
        subscribes = db.GqlQuery("SELECT * FROM Subscribe WHERE userName=:1 AND maincode=:2",userName,maincode)
        if (subscribes):
            for subscribe in subscribes:
                if subscribe.status=='1':
                    subscribe.status = '0'
                    subscribe.lastUpdateTime = datetime.datetime.now()
                    db.put(subscribe)
                else:
                    subscribe.status = '1'
                    subscribe.lastUpdateTime = datetime.datetime.now()
                    db.put(subscribe)
        self.redirect('/subscribeList?searchType=%s' %userName)

class SubscribeOtherAdd(PublicPage):
    @login_required
    def get(self):
        maincode = self.request.get('maincode')
        userName = self.request.get('userName')
        contents = []
        replyContents = db.GqlQuery("SELECT * FROM ReplyContent WHERE father=:1",maincode)
        conts = db.GqlQuery("SELECT * FROM ContentClass WHERE father=:1",maincode)
        
        if replyContents:
            for replyContent in replyContents:
                contents.append(replyContent)
        if conts:
            for cont in conts:
                contents.append(cont)
                
        template_values = {'userName':userName,"contents":contents,}
        self.render('template/subscribe/subscribeOtherAdd.html',template_values)#本地上运行用这个
#        self.render('html/subscribeManage/subscribeOtherAdd.html',template_values)#本地上运行用这个
    @login_required
    def post(self):
        greeting = SubscribeOther()
        userName = greeting.userName = self.request.get('userName')
        maincode = greeting.maincode = self.request.get('maincode')
        code = greeting.code = self.request.get('code')
        level=self.request.get('level')
        father=self.request.get('father')
        subscribeOthers = db.GqlQuery("SELECT * FROM SubscribeOther WHERE maincode=:1 AND userName=:2 AND code=:3",greeting.maincode,greeting.userName,greeting.code)
        subscribeOther = subscribeOthers.fetch(1,0)
        if subscribeOther:
            self.redirect('/userSubscribeAdd?maincode=%s&userName=%s&father=%s' %(greeting.maincode,greeting.userName,father))
            return
          
        greeting.father = father
        greeting.level = level
        greeting.subscribeType = self.request.get('subscribeType')
        greeting.put()
        
#        if greeting.subscribeType == '0':#如果是 "全要"
#            contentList = []
#            contentList = findChildNodes(contentList,code)
#            for cList in contentList:
#                Sgreeting = SubscribeOther()
#                Sgreeting.maincode=cList.maincode#资讯编号
#                Sgreeting.code=cList.code
#                Sgreeting.subscribeType = '0' #下面全要
#                Sgreeting.userName = userName#用户名
#                Sgreeting.father = cList.father#父类
#                Sgreeting.level = cList.level#资讯等级
#                Sgreeting.put()#调用方法
        ####更改时间        
#        greeting = Subscribe()
#        subscribes = db.GqlQuery("SELECT * FROM Subscribe WHERE userName=:1 AND maincode=:2",userName,maincode)
#        if subscribes:
#            for subscribe in subscribes:
#                subscribe.DownLastUpdateTime = datetime.datetime.now()
#                db.put(subscribe)
        self.redirect('/subscribeOtherList?userName=%s&father=%s&level=%s' %(userName,father,int(level)-1))

        
class SubscribeOtherList(PublicPage):
    @login_required
    def get(self):
        father = self.request.get('father')
        userName = self.request.get('userName')
        level = str(string.atoi(self.request.get('level'))+1)
#        subscribeType = self.request.get('subscribeType')
#        if subscribeType=='':
#            subscribeType ='1'
#        if subscribeType=='0':
#            subscribeOthers = db.GqlQuery("SELECT * FROM SubscribeOther WHERE userName=:1 AND father=:2 AND level=:3",userName,maincode,level)
#            #AddNewContent(userName,maincode)
#        if subscribeType=='1':
        subscribeOthers = db.GqlQuery("SELECT * FROM SubscribeOther WHERE userName=:1 AND father=:2  ORDER BY maincode ,code",userName,father)
        template_values = {"subscribeOthers":subscribeOthers,"userName":userName,"level":level,'father':father}
        self.render('template/subscribe/subscribeOtherList.html',template_values)#本地上运行用这个
#        self.render('html/subscribeManage/subscribeOtherList.html',template_values)#本地上运行用这个


class SubscribeOtherDelete(PublicPage):
    @login_required
    def get(self):
        userName = self.request.get('userName')
        maincode = self.request.get('maincode')
        code = self.request.get('code')
        subscribeOthers = db.GqlQuery("SELECT * FROM SubscribeOther WHERE userName=:1 AND code=:2",userName,code)
        if (subscribeOthers):
            contentList = []
            for subscribeOther in subscribeOthers:
                father = subscribeOther.father
                level = subscribeOther.level
                contentList.append(subscribeOther)
                contentList=findSubscribeOthers(contentList,userName,code)
        for cList in contentList:
            db.delete(cList)
        #删除成功后，把第一层的subscribeType改为1（下面的另外订阅，0是全部订阅）。
        subscribes = db.GqlQuery("SELECT * FROM Subscribe WHERE userName=:1 AND maincode=:2",userName,maincode)
        if subscribes:
            for subscribe in subscribes:
                subscribe.subscribeType = '1'
                db.put(subscribe)
        father_subscribeOthers = db.GqlQuery("SELECT * FROM SubscribeOther WHERE userName=:1 AND code=:2",userName,father)
        if (father_subscribeOthers):
            for father_subscribeOther in father_subscribeOthers:
                father_subscribeOther.subscribeType = '1'
                db.put(father_subscribeOther)
        self.redirect('/subscribeOtherList?userName=%s&father=%s&level=%s' %(userName,father,str(string.atoi(level)-1)))


##########搜索是否有子节点############
def findChildNodes(contentList,currentCode):
    replyContents = db.GqlQuery("SELECT * FROM ReplyContent WHERE father=:1 ",currentCode)
    contents = db.GqlQuery("SELECT * FROM ContentClass WHERE father=:1 ",currentCode)
    if replyContents:
        for replyContent in replyContents:
            contentList.append(replyContent)
            findChildNodes(contentList,replyContent.code)

    if contents:
        for content in contents:
            contentList.append(content)
            findChildNodes(contentList,content.code)
        
    return contentList
  
##########搜索订阅资讯的子节点###########
def findSubscribeOthers(contentList,userName,currentCode):
    subscribeOthers = db.GqlQuery("SELECT * FROM SubscribeOther WHERE userName=:1 AND father=:2 ",userName,currentCode)
    if subscribeOthers:
        for subscribeOther in subscribeOthers:
            contentList.append(subscribeOther)
            findSubscribeOthers(contentList,userName,subscribeOther.code)
    return contentList 


def AddNewContent(userName,currentCode):
    replyContents = db.GqlQuery("SELECT * FROM ReplyContent WHERE maincode=:1 and level>'1'",currentCode)
    contents = db.GqlQuery("SELECT * FROM ContentClass WHERE maincode=:1 and level>'1'",currentCode)
    
    if replyContents.count():
        for replyContent in replyContents:
            subscribeOthers = db.GqlQuery("SELECT * FROM SubscribeOther WHERE userName=:1 AND code=:2 ",userName,replyContent.code)
            if  subscribeOthers.count()==0:
                greeting = SubscribeOther()
                greeting.userName = userName
                greeting.maincode = replyContent.maincode
                greeting.code = replyContent.code
                greeting.subscribeType = '0' #下面全要
                greeting.father = replyContent.father
                greeting.level = replyContent.level
                greeting.put()

    if contents.count():
        for content in contents:
            subscribeOthers = db.GqlQuery("SELECT * FROM SubscribeOther WHERE userName=:1 AND code=:2 ",userName,content.code)
            if  subscribeOthers.count()==0:
                greeting = SubscribeOther()
                greeting.userName = userName
                greeting.maincode = content.maincode
                greeting.code = content.code
                greeting.subscribeType = '0' #下面全要
                greeting.father = content.father
                greeting.level = content.level
                greeting.put()
